from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QMessageBox

from src.main.server.controller.login_controller import LoginController


class LoginUiLoader:
    def __init__(self, controller=None):
        self.ui_file_path = "../../../qt_ui/login.ui"
        self.window = None
        self.controller = controller
        self._load_ui()

    def _load_ui(self):
        file = QFile(self.ui_file_path)
        try:
            self.window = QUiLoader().load(file)
            self.window.pushButton.clicked.connect(self.show_confirmation_dialog)
            self.window.pushButton_2.clicked.connect(self.clear)
            self.window.pushButton_3.clicked.connect(self.checkout_register_window)
        finally:
            file.close()


    def clear(self):
        print("清除表单数据")
        self.window.lineEdit.clear()
        self.window.lineEdit_2.clear()

    def login_check(self):
        """登录检查"""

        username = self.window.lineEdit.text()
        password = self.window.lineEdit_2.text()

        if username:
            print(f"用户输入的账号为：{username}")
        else:
            print("请输入账户名")
            return
        if password:
            print(f"用户输入的密码为：{password}")
        else:
            print("请输入密码")
            return

        result = LoginController().login(username, password)
        if result:
            print("登录成功")
            print("模拟进入用户界面")
            self.checkout_main_window()
        else:
            print("密码错误或账户不存在，请重新输入")

    def show_confirmation_dialog(self):
        # 使用 self.window 作为父级窗口
        reply = QMessageBox.question(
            self.window,
            "确认",
            "是否确定执行此操作？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            print("用户选择继续登录")
            self.login_check()
        else:
            print("用户取消登录")


    def checkout_register_window(self):
        """切换成注册界面"""
        print("进入注册UI")
        self.window.close()
        if self.controller:
            self.controller.show_register()


    def checkout_main_window(self):
        """切换成用户界面"""
        print("进入用户界面UI")
        self.window.close()
        if self.controller:
            self.controller.show_main()
